<script setup lang="ts">
import {
  addPaymentProjectApi,
  deletePaymentProjectApi,
  getAllPaymentProjectByIdApi,
  updatePaymentProjectApi,
} from '@src/apis/paymentProjectApi.ts'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import {
  ElTable,
  FormInstance,
  genFileId,
  UploadInstance,
  UploadProps,
  UploadRawFile,
} from 'element-plus'
import { onMounted, onUnmounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getImageUrlByImageName, uploadImageApi } from '@src/apis/imageApi.ts'
import useUserStore from '@src/stores/useUserStore.ts'
import { storeToRefs } from 'pinia'
import { EnumUserRole } from '@src/enums/EnumUserRole.ts'
import { router } from '@util/RouterUtil.ts'
import TokenUtil from '@util/TokenUtil.ts'
import formatDate from '../../../utils/formatDate.ts'
import Pagination from '@src/components/Pagination.vue'
import type { FormRules } from 'element-plus'
import ImagePreview from '@src/components/ImagePreview.vue'
var data = ref({
  id: 13,
  title: '测试1111',
  description: '测试',
  amount: 100,
  deadLine: new Date(),
  imageName: '测试',
  classId: 1,
})
interface PaymentProject {
  id: number
  title: string
  description: string
  amount: number
  classId: number
  deadLine: Date
  imageName: ''
  isDelete: string
}

// 用户信息
const userStore = useUserStore()
const userInfo = storeToRefs(userStore).userInfo
// 储存全部缴费记录变量
const tableData = ref<PaymentProject[]>([])
// 展示某条缴费记录信息变量
const itemFormData = ref({
  id: 0,
  title: '',
  description: '',
  amount: '',
  classId: 0,
  deadLine: new Date(),
  imageName: '',
})
// 添加消息表单变量
const addFormData = ref({
  id: 0,
  title: '',
  description: '',
  amount: '',
  classId: 0,
  deadLine: new Date().getTime() + 1000 * 3600 * 24 * 7,
  imageName: '',
})
// 修改消息表单数据绑定变量
const editFormData = ref({
  id: 0,
  title: '',
  description: '',
  amount: '',
  classId: 0,
  deadLine: new Date(),
  imageName: '',
})
// 显示展示某条缴费信息表单框变量
const infoVisible = ref(false)
// 显示修改某条缴费信息表单框变量
const editVisible = ref(false)
// 显示添加缴费信息表单框变量
const addVisible = ref(false)
// 修改消息表单数据校验变量
const editFormRef = ref<FormInstance>()
const addFormRef = ref<FormInstance>()
// 发布缴费项目发布金额表单验证
const addFormRule = ref<FormRules<typeof addFormData>>({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
  deadLine: [
    { required: true, message: '请选择缴费截止时间', trigger: 'blur' },
  ],
  imageName: [{ required: true, message: '请选择缴费二维码', trigger: 'blur' }],
})
const editFormRule = ref<FormRules<typeof editFormData>>({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
  deadLine: [
    { required: true, message: '请选择缴费截止时间', trigger: 'blur' },
  ],
  imageName: [{ required: true, message: '请选择缴费二维码', trigger: 'blur' }],
})
// 当前显示的是第几页
const currentPage = ref(1)
// 每页显示多少条
const pageSize = ref(2)
// 总记录条数
const total = ref(0)
// 搜索信息
const searchInfo = ref('')
// 钩子函数调用查询函数
onMounted(() => {
  TokenUtil.refresh().then(() => {
    if (userInfo.value.role !== EnumUserRole.CLASS_ADMIN) {
      ElMessage.warning('权限不足,返回首页')
      router.push('/')
      return
    }
    getAllPaymentProjectById(
      currentPage.value,
      pageSize.value,
      searchInfo.value,
    )
  })
})

// 得到全部缴费项目或者搜索缴费项目
const getAllPaymentProjectById = (
  page: number,
  size: number,
  search: string,
) => {
  getAllPaymentProjectByIdApi(page, size, search).then((res) => {
    tableData.value = res.data.data.records
    total.value = res.data.data.total
  })
}
// 删除缴费项目
const deletePaymentProject = (paymentProjectId: number) => {
  deletePaymentProjectApi(paymentProjectId).then((obj) => {
    if (obj.data.code == 200) {
      ElMessage.success(obj.data.message)
      getAllPaymentProjectById(
        currentPage.value,
        pageSize.value,
        searchInfo.value,
      )
    } else {
      ElMessage.error(obj.data.message)
    }
  })
}
// 添加缴费项目
const addPaymentProject = () => {
  addFormRef.value?.validate((value) => {
    if (!value) {
      return
    }
    addVisible.value = true
    addPaymentProjectApi(addFormData.value).then((obj) => {
      ElMessage.success(obj.data.message)
      addHandleDialogClose()
      addFormRef.value?.resetFields()
      getAllPaymentProjectById(
        currentPage.value,
        pageSize.value,
        searchInfo.value,
      )
    })
  })
}
// 修改缴费项目
const updatePaymentProject = () => {
  editFormRef.value?.validate((value) => {
    if (!value) {
      return
    }
    updatePaymentProjectApi(editFormData.value).then((obj) => {
      ElMessage.success(obj.data.message)
      editHandleDialogClose()
    })
  })
}
const handleInfo = (row: PaymentProject) => {
  infoVisible.value = true
  itemFormData.value = row
}
const handleDelete = (row: PaymentProject) => {
  deletePaymentProject(row.id)
}
const handleEdit = (row: PaymentProject) => {
  editVisible.value = true
  editFormData.value = row
}
const infoHandleDialogClose = () => {
  infoVisible.value = false
}

const editHandleDialogClose = () => {
  editVisible.value = false
}
const addHandleDialogClose = () => {
  addVisible.value = false
}
//显示添加缴费项目表单框
const addHandleDialogShow = () => {
  addVisible.value = true
}
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getAllPaymentProjectById(currentPage.value, pageSize.value, searchInfo.value)
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getAllPaymentProjectById(currentPage.value, pageSize.value, searchInfo.value)
}
//添加缴费二维码
// 提交缴费二维码
// @ts-ignore
const editUpload = (content) => {
  uploadImageApi(content.raw).then((obj) => {
    editFormData.value.imageName = obj.data
  })
}
const addUpload = (content) => {
  uploadImageApi(content.raw).then((obj) => {
    addFormData.value.imageName = obj.data
  })
}
// 根据标题或者描述搜索缴费
const searchPaymentProject = () => {
  getAllPaymentProjectById(currentPage.value, pageSize.value, searchInfo.value)
}
function isDeadlined(deadLine: string) {
  return new Date().getTime() - new Date(deadLine).getTime() >= 0
}

/**预览图片*/
const imagePreviewProps = ref({
  show: false,
  src: '',
  alt: '',
})
onMounted(() => {
  const previewListener = () => {
    const listener = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (target.tagName.toLowerCase() !== 'img') return

      const imgEl = target as HTMLImageElement
      imagePreviewProps.value.src = imgEl.src
      imagePreviewProps.value.alt = imgEl.alt
      imagePreviewProps.value.show = true
    }
    window.addEventListener('click', listener)

    return () => {
      window.removeEventListener('click', listener)
    }
  }
  const removePreviewListener = previewListener()
  onUnmounted(() => {
    removePreviewListener()
  })
})
</script>

<template>
  <div class="over-all">
    <h2><el-text>缴费项目管理</el-text></h2>
    <!--    发布缴费项目搜索项目标题或者内容-->
    <div class="add-search">
      <el-input
        v-model="searchInfo"
        placeholder="请输入搜索缴费项目标题或者内容"
      ></el-input>
      <el-button type="primary" @click="addHandleDialogShow"> 发布 </el-button>
      <el-button type="primary" @click="searchPaymentProject"> 搜索 </el-button>
    </div>

    <!--  展示缴费项目-->
    <el-table
      height="620"
      :data="tableData"
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column property="title" label="项目标题" />
      <el-table-column property="amount" label="金额" />
      <el-table-column property="deadLine" label="截止时间">
        <template #default="scope">
          {{ formatDate(scope.row.deadLine) }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-text type="danger" v-if="scope.row.isDelete == '已删除'">
            已删除
          </el-text>
          <el-text v-else-if="isDeadlined(scope.row.deadLine)">
            已截止
          </el-text>
          <el-text v-else type="success"> 正常 </el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="270px">
        <template #default="scope">
          <div class="operation">
            <el-button
              v-if="scope.row.isDelete != '已删除'"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button @click="handleInfo(scope.row)"> 查看详情 </el-button>
            <el-button
              type="primary"
              v-if="
                scope.row.isDelete != '已删除' &&
                !isDeadlined(scope.row.deadLine)
              "
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--    查看缴费项目详情-->
    <div class="paymentRecordInfo">
      <el-dialog
        width="400"
        v-model="infoVisible"
        title="查看缴费信息"
        :before-close="infoHandleDialogClose"
        center
      >
        <el-form label-width="120px">
          <el-form-item label="缴费项目标题">
            <el-input
              v-model="itemFormData.title"
              style="width: 210px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费项目描述">
            <el-input
              type="textarea"
              v-model="itemFormData.description"
              style="width: 210px"
              disabled
              class="textArea"
              rows="5"
              resize="none"
              readonly
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费金额(元)">
            <el-input
              v-model="itemFormData.amount"
              style="width: 210px"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="截止时间">
            <div class="block">
              <el-date-picker
                v-model="itemFormData.deadLine"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
                disabled
              />
            </div>
          </el-form-item>
          <el-form-item label="缴费二维码">
            <img
              :src="getImageUrlByImageName(itemFormData.imageName)"
              style="width: 100px; height: 100px; margin-left: 25px"
              alt=""
            />
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!--    修改缴费项目-->
    <div class="paymentRecordInfo">
      <el-dialog
        width="400"
        v-model="editVisible"
        title="查看缴费信息"
        :before-close="editHandleDialogClose"
        center
      >
        <el-form
          :model="editFormData"
          ref="editFormRef"
          :rules="editFormRule"
          label-width="120px"
        >
          <el-form-item label="缴费项目标题" prop="title">
            <el-input
              v-model="editFormData.title"
              style="width: 210px"
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费项目描述" prop="description">
            <el-input
              type="textarea"
              v-model="editFormData.description"
              style="width: 210px"
              class="textArea"
              rows="5"
              resize="none"
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费金额(元)" prop="amount">
            <el-input
              v-model="editFormData.amount"
              style="width: 210px"
            ></el-input>
          </el-form-item>
          <el-form-item label="截止时间" prop="deadLine">
            <div class="block">
              <el-date-picker
                v-model="editFormData.deadLine"
                type="datetime"
                placeholder="选择截止时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
              />
            </div>
          </el-form-item>
          <el-form-item label="缴费二维码" prop="imageName">
            <el-upload
              :show-file-list="false"
              :auto-upload="false"
              @change="editUpload"
            >
              <el-image
                :src="getImageUrlByImageName(editFormData.imageName)"
                style="width: 100px; height: 100px; margin-left: 25px"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /> </el-icon>
                  </div>
                </template>
              </el-image>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="warning"
              @click="editHandleDialogClose"
            >
              取消
            </el-button>
            <el-button
              size="default"
              type="success"
              @click="updatePaymentProject"
            >
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!--    添加缴费项目-->
    <div class="paymentRecordInfo">
      <el-dialog
        width="400"
        v-model="addVisible"
        title="添加缴费信息"
        :before-close="addHandleDialogClose"
        center
      >
        <el-form
          :model="addFormData"
          ref="addFormRef"
          :rules="addFormRule"
          label-width="120px"
        >
          <el-form-item label="缴费项目标题" prop="title">
            <el-input
              v-model="addFormData.title"
              style="width: 210px"
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费项目描述" prop="description">
            <el-input
              type="textarea"
              v-model="addFormData.description"
              style="width: 210px"
              class="textArea"
              rows="5"
              resize="none"
            ></el-input>
          </el-form-item>
          <el-form-item label="缴费金额(元)" prop="amount">
            <el-input
              v-model="addFormData.amount"
              style="width: 210px"
            ></el-input>
          </el-form-item>
          <el-form-item label="截止时间" prop="deadLine">
            <div class="block">
              <el-date-picker
                v-model="addFormData.deadLine"
                type="datetime"
                placeholder="请点击选择截止时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
              />
            </div>
          </el-form-item>
          <el-form-item label="缴费二维码" prop="imageName">
            <el-upload
              :show-file-list="false"
              :auto-upload="false"
              @change="addUpload"
            >
              <el-image
                :src="getImageUrlByImageName(addFormData.imageName)"
                style="width: 100px; height: 100px"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /> </el-icon>
                  </div>
                </template>
              </el-image>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="warning"
              @click="addHandleDialogClose"
            >
              取消
            </el-button>
            <el-button size="default" type="success" @click="addPaymentProject">
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!--    分页-->
    <Pagination
      :page="currentPage"
      :size="pageSize"
      @size-change="handleSizeChange"
      @page-change="handleCurrentChange"
      :total="total"
    >
    </Pagination>
    <image-preview
      v-model:show="imagePreviewProps.show"
      v-model:src="imagePreviewProps.src"
      v-model:alt="imagePreviewProps.alt"
    />
  </div>
</template>

<style scoped lang="less">
.over-all {
  h2 {
    text-align: center;
    .el-text {
      font-size: 2em;
    }
  }
}
.add-search {
  display: flex;
  & > * {
    margin: 0 10px;
  }
}
.page {
  position: fixed;
  bottom: 5px;
  left: 210px;
}
.operation {
  display: flex;
  justify-content: space-between;
}
.upload-demo {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.el-image {
  padding: 0 5px;
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 200px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 30px;
}
</style>
